// 支付相关API接口
import type { OrderInfo } from '@/store/payment'

// 模拟API请求延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

// 模拟API响应数据
interface ApiResponse<T> {
  code: number
  message: string
  data: T
}

// 创建订单请求参数
interface CreateOrderRequest {
  deviceId: string
  amount: number
}

// 创建订单响应数据
interface CreateOrderResponse {
  orderId: string
  paymentUrl?: string
}

// 创建订单
export async function createOrder(data: CreateOrderRequest): Promise<ApiResponse<CreateOrderResponse>> {
  // 模拟网络请求
  await delay(1000)
  
  // 模拟创建订单
  const orderId = 'O' + Date.now()
  
  return {
    code: 200,
    message: '订单创建成功',
    data: {
      orderId,
      paymentUrl: `/pages/payment/checkout?orderId=${orderId}`
    }
  }
}

// 获取订单详情
export async function getOrderDetail(orderId: string): Promise<ApiResponse<OrderInfo | null>> {
  // 模拟网络请求
  await delay(500)
  
  // 模拟订单数据
  const order: OrderInfo = {
    id: orderId,
    deviceId: 'D001',
    deviceName: '1号洗车机',
    amount: 15,
    status: 'pending',
    createdAt: new Date().toISOString()
  }
  
  return {
    code: 200,
    message: '获取成功',
    data: order
  }
}

// 模拟支付
export async function payOrder(orderId: string, paymentMethod: string): Promise<ApiResponse<{ status: 'success' | 'failed' }>> {
  // 模拟网络请求
  await delay(2000)
  
  // 模拟支付结果（90%成功率）
  const isSuccess = Math.random() > 0.1
  
  return {
    code: 200,
    message: isSuccess ? '支付成功' : '支付失败',
    data: {
      status: isSuccess ? 'success' : 'failed'
    }
  }
}

// 获取用户余额
export async function getUserBalance(): Promise<ApiResponse<{ balance: number }>> {
  // 模拟网络请求
  await delay(500)
  
  // 模拟用户余额
  return {
    code: 200,
    message: '获取成功',
    data: {
      balance: 100
    }
  }
}

// 余额支付
export async function payWithBalance(orderId: string, amount: number): Promise<ApiResponse<{ status: 'success' | 'failed' }>> {
  // 模拟网络请求
  await delay(1500)
  
  // 模拟支付结果（95%成功率）
  const isSuccess = Math.random() > 0.05
  
  return {
    code: 200,
    message: isSuccess ? '支付成功' : '余额不足',
    data: {
      status: isSuccess ? 'success' : 'failed'
    }
  }
}